<template>
	<view class="login-box">
		<view class="login-header">
			<view class="back-icon" @click="goBack">
				<image src="/static/icon/left.svg" mode=""></image>
			</view>
		</view>
		<view class="login-title">
			<text>{{ t("login.hyhl") }}</text>
		</view>
		<view class="login-subtitle syl">
			<text>{{ t("login.qsynd") }}</text>
		</view>
		
		<view class="login-form">
			<u-form :model="formData" ref="uForm" errorType="message">
				<!-- 邮箱输入框 -->
				<view class="form-item" :class="{active:active=='email'}">
					<u-input
						v-model="formData.email"
						:placeholder="t('login.qsryhm')"
						border="none"
						size="large"
						placeholderStyle="color: #9EA3AE; font-size: 24rpx; font-family: SYL"
						inputAlign="left"
						@blur="active=''"
						@focus="active='email'"
					>
						<template #prefix>
							<image class="input-icon" src="/static/icon/user-icon.svg" style="width: 27.91rpx;height: 34.88rpx; margin-left: 14rpx;"></image>
						</template>
					</u-input>
				</view>
				
				<!-- 密码输入框 -->
				<view class="form-item" :class="{active:active=='password'}">
					<u-input
						v-model="formData.password"
						:placeholder="t('login.mm')"
						border="none"
						size="large"
						:password="!showPassword"
						placeholderStyle="color: #9EA3AE; font-size: 24rpx; font-family: SYL"
						inputAlign="left"
						@blur="active=''"
						@focus="active='password'"
					>
						<template #prefix>
							<image class="input-icon" src="/static/icon/password-icon.svg"></image>
						</template>
						<template #suffix>
							<image 
								class="password-icon" 
								:src="showPassword ? '/static/icon/eye-open.svg' : '/static/icon/eye-close.svg'"
								@click="togglePasswordVisibility"
							></image>
						</template>
					</u-input>
				</view>
			</u-form>
			
			<!-- 服务条款和隐私政策 -->
			<view class="agreement-box">
				<text class="agreement-link" @click="goToForget">{{ t('login.wjmm') }}</text>
			</view>
		</view>
		
		<view class="bottom-box">
			<!-- 创建账户按钮 -->
			<view class="login-btn btn-primary" @click="submitForm" :class="{loading: isLoading}">
				{{ isLoading ? '登录中...' : t('login.dlzh') }}
			</view>
			
			<!-- 已经注册？登录 -->
			<view class="login-link syl">
				<text>{{ t('login.myzh') }}</text>
				<text class="login-text" @click="goToRegister">{{ t('login.zc') }}</text>
			</view>
		</view>
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { authApi } from '@/api/auth.js';
import TokenManager from '@/utils/token.js';

const popup = ref()
const { t } = useI18n();
const active = ref("")
const isLoading = ref(false)

// 表单数据 - 修改为email字段
const formData = reactive({
	email: '',
	password: '',
});

// 密码显示控制
const showPassword = ref(false);
const togglePasswordVisibility = () => {
	showPassword.value = !showPassword.value;
};

// 返回上一页
const goBack = () => {
	uni.navigateBack();
};

// 邮箱或用户名格式验证
const validateEmailOrUsername = (input) => {
	// 邮箱格式验证
	const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
	// 用户名格式验证（3-20位字母、数字、下划线）
	const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
	
	return emailRegex.test(input) || usernameRegex.test(input);
};

// 提交表单
const submitForm = async () => {
	// 表单验证
	if (!formData.email) {
		popup.value.open({
			title: t('login.qsryhm'),
			loading: false
		})
		return;
	}
	
	if (!validateEmailOrUsername(formData.email)) {
		popup.value.open({
			title: '请输入正确的用户名或邮箱格式',
			loading: false
		})
		return;
	}
	
	if (!formData.password) {
		popup.value.open({
			title: t('login.qsrmm'),
			loading: false
		})
		return;
	}

	if (formData.password.length < 6) {
		popup.value.open({
			title: '密码长度不能少于6位',
			loading: false
		})
		return;
	}

	// 开始登录
	isLoading.value = true;
	
	try {
		console.log('提交登录信息', formData);
		
		// 调用登录接口
		const response = await authApi.loginByEmail({
			email: formData.email,
			password: formData.password
		});

		console.log('登录响应:', response);

		if (response.code === 0 && response.data) {
			// 登录成功，保存令牌信息
			TokenManager.setLoginInfo(response.data);
			
			// 显示成功提示
			uni.showToast({
				title: '登录成功',
				icon: 'success'
			});

			// 跳转到首页
			setTimeout(() => {
				uni.switchTab({
					url: "/pages/home/home"
				});
			}, 1000);
		} else {
			// 登录失败
			popup.value.open({
				title: '登录失败',
				content: response.msg || '用户名或密码错误',
				loading: false
			});
		}
	} catch (error) {
		console.error('登录错误:', error);
		
		// 显示错误信息
		popup.value.open({
			title: '登录失败',
			content: error.msg || error.message || '网络错误，请稍后重试',
			loading: false
		});
	} finally {
		isLoading.value = false;
	}
};

// 跳转到注册页面
const goToRegister = () => {
	uni.navigateTo({
		url: '/pages/account/register'
	});
};

// 跳转到找回密码页面
const goToForget = () => {
	uni.navigateTo({
		url: '/pages/account/forget'
	});
};

// 组件卸载时清除定时器
onUnmounted(() => {
	// 清理工作
});
</script>

<style lang="scss">
	.bottom-box{
		padding:0 0 80rpx;
		margin-top: 20vh;
	}
.login-box {
	padding: 0 40rpx;
	height: 100vh;
	background-color: #fff;
	
	.login-header {
		padding-top: 88rpx;
		display: flex;
		align-items: center;
		
		.back-icon {
			width: 69.77rpx;
			height: 69.77rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			border-radius: 17.44rpx;
			border: 1.74rpx solid #EFF6FF;
			
			image {
				width: 10.47rpx;
				height: 20.93rpx;
			}
		}
	}
	
	.login-title {
		margin: 60rpx 32rpx 0;
		font-size: 48rpx;
		color: #000000;
		font-weight: 500;
		line-height: 1.2;
	}
	
	.login-subtitle {
		margin: 22.65rpx 32rpx 0;
		font-size: 28rpx;
		color: #6C727F;
		margin-bottom: 60.98rpx;
	}
	
	.login-form {
		margin:  0 32rpx;
		.code-box{
			display: flex;
			justify-content: space-between;
			align-items: center;
			.send-btn{
				flex: 1;
				width: 200.58rpx;
				line-height: 97.67rpx;
				border-radius: 27.91rpx;
				background: #0278DC;
				font-size: 27.91rpx;
				font-weight: 400;
				color: #fff;
				margin-bottom: 27.87rpx;
				margin-left: 33.1rpx;
				text-align: center;
				transition: all 0.3s;
				
				&.counting {
					background: rgba(2, 120, 220, 0.5)
				}
			}
			.form-item{
				flex: 1;
			}
		}
		.form-item {
			margin-bottom: 27.87rpx;
			border-radius: 27.91rpx;
			background: rgba(249, 250, 251, 1);
			padding: 24rpx 60.2rpx;
			border: 1px solid transparent;
			height: 100rpx;
			box-sizing: border-box;
			.input-icon {
				width: 41.86rpx;
				height: 41.86rpx;
				margin-right: 26rpx;
				transform: translateY(4px);
			}
			:deep(.uni-input-wrapper) {
				font-size: 28rpx;
				color: #121826;
				font-family: "SYL";
			}
			:deep(.u-input__content__subfix-password-shower) span{
				display: none;
			}
			.password-icon {
				width: 44rpx;
				height: 44rpx;
			}
			&.active{
				border: 1.74rpx solid rgba(59, 130, 246, 1);
			}
		}
		
		
		.agreement-box {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			justify-content: end;
			margin-top: 30rpx;
			margin-bottom: 80rpx;
			padding-left: 10rpx;
			.agreement-text {
				font-size: 24rpx;
				color: #394150;
				line-height: 1.5;
			}
			
			.agreement-link {
				font-size: 24rpx;
				color: #0278DC;
				line-height: 1.5;
			}
		}
	}
	
	.login-btn {
		width: 570.35rpx;
		height: 97.67rpx;
		border-radius: 26.16rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #FFFFFF;
		font-size: 32rpx;
		font-weight: 500;
		margin: 60rpx auto 0;
	}
	
	.login-link {
		margin-top: 15.68rpx;
		text-align: center;
		font-size: 28rpx;
		line-height: 40.41rpx;
		font-size: 27.91rpx;
		font-weight: 400;
		color:#9EA3AE;
		
		.login-text {
			color: #0278DC;
			margin-left: 6rpx;
		}
	}
}
</style>